//
//  main.c
//  TCP服务器
//
//  Created by lu on 2024/1/7.
//

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 5001
#define BACKLOG 5

int main(int argc, const char * argv[]) {
    int fd;
    char buf[BUFSIZ] = {"Hello World!"};
    struct sockaddr_in addr;
    int port = PORT;
    if(argc < 3){
    }else{
        port = atoi(argv[2]);
    }
    printf("port = %d\n",port);
    //创建套接字。
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("socket");
        exit(0);
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if ( argv[1]) {
        if ( inet_aton(argv[1], &addr.sin_addr) == 0) {
            fprintf(stderr, "Invalid address\n");
            exit(EXIT_FAILURE);
        }
    }
    int ret = connect(fd, (const struct sockaddr *)&addr, sizeof(addr));
    //像向服务端发起连接请求。
    if (ret == -1) {
        perror("connect");
        exit(0);
    }
    while (1)
    {
        printf("Input->");
        fgets(buf,BUFSIZ,stdin);
        write(fd, buf, sizeof(buf));
        printf("BUF = %s\n",buf);
    }
    
    close(fd);
    return 0;
}
